package utils

import (
	"io/ioutil"

	"gopkg.in/yaml.v2"
)

type Yaml struct {
	Mysql Mysql
}

type Mysql struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Protocol string `yaml:"protocol"`
	User     string `yaml:"user"`
	Passwd   string `yaml:"passwd"`
	DBname   string `yaml:"dbname"`
}

func LoadConf(confFile string) Yaml {
	conf := new(Yaml)
	yamlFile, err := ioutil.ReadFile(confFile)
	if err != nil {
		Error.Fatalf("配置文件%s加载失败: %v\n", confFile, err)
	}

	err = yaml.Unmarshal(yamlFile, conf)
	if err != nil {
		Error.Fatalf("配置文件%s解析失败: %v\n", confFile, err)
	}

	if conf.Mysql.Host == "" {
		conf.Mysql.Host = "localhost"
	}
	if conf.Mysql.Port == 0 {
		conf.Mysql.Port = 3306
	}
	if conf.Mysql.Protocol == "" {
		conf.Mysql.Protocol = "tcp"
	}
	if conf.Mysql.User == "" {
		conf.Mysql.User = "root"
	}
	if conf.Mysql.Passwd == "" {
		conf.Mysql.Passwd = "broadtech"
	}
	return *conf
}
